from django.shortcuts import render
from  utils.pageTool import get_objects_page
from .models import *

from django.views import View
from django.http import HttpResponse
# Create your views here.
def wrapper_recommend_goods_cookie(func):
    def _wrapper(detailview,request,goods_id,*args,**kwargs):
        raw_remcommend_goods=request.COOKIES.get('recommend_goods','')
        goods_list = [item for item in raw_remcommend_goods.split() if item.strip()]
        recommend_goods = [Goods.objects.get(id=gid)  for gid in goods_list if gid !=goods_id and
                           Goods.objects.get(id = goods_id).category_id == Goods.objects.get(id=gid).category_id][:4]
        response=func(detailview,request,goods_id,recommend_goods,*args,**kwargs)


        goods_id=str(goods_id)
        if goods_id not in goods_list:
            goods_list.append(goods_id)
        else:
            goods_list.remove(goods_id)
            goods_list.insert(0,goods_id)
        response.set_cookie('recommend_goods',' '.join(goods_list),max_age=60*60*24*3)
        return response
    return _wrapper
class TestView(View):

    def get(self,request,pagenum=1):
        object_list=Goods.objects.all()
        page,goodses = get_objects_page(object_list,pagenum,5)
        page_range=page.paginator.page_range
        return render(request, 'test.html', {'goodses':goodses, 'page_range':page_range})


class IndexView(View):
    category = Category.objects.all()
    current_category_id = Category.objects.first().id
    def get(self,request,category_id=None,pagenum=1):
        if category_id==None:
            current_cid = self.current_category_id
        else:
            current_cid=category_id
        pages,goods=get_objects_page(Goods.objects.filter(category_id=current_cid),pagenum)
        return render(request,'index.html',{'categorys':self.category,'current_cid':int(current_cid),'pages':pages,'goods':goods})
class DetailView(View):
    @wrapper_recommend_goods_cookie
    def get(self,request,goods_id,recommend_goods=[]):
        goods = Goods.objects.get(id=int(goods_id))
        return  render(request,'detail.html',{'goods':goods,'recommend_goods':recommend_goods})